package com.konne.nightmare.FastPublicOpinion.widget;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class HorizontalItemDecoration extends RecyclerView.ItemDecoration {
    private int space1;//定义2个Item之间的距离
    private int space2;//定义2个Item之间的距离
    private int type;//0上1下2左3右4上和右
    public static final int TOP = 0x005;
    public static final int STAND_ITEM_DECORATION = 0x006;
    public static final int TOP_START_END = 0x007;

    public HorizontalItemDecoration(Context context, int space1, int space2, int type) {
        this.space1 = dip2px(context, space1);
        this.space2 = dip2px(context, space1);
        this.type = type;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {

        switch (type) {
            case 0:
                if (parent.getChildCount() == 1) {
                    return;
                }
                outRect.top = space1;
                break;
            case 1:
                outRect.bottom = space1;
                break;
            case 2:
                outRect.left = space1;
                break;
            case 3:
                outRect.right = space1;
                break;
            case 4:
                RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
                int mSpanCount = ((GridLayoutManager) layoutManager).getSpanCount();
                if (parent.getChildCount() % mSpanCount != 0) {//第一个
                    outRect.right = space2;
                }
                if (parent.getChildCount() != 1) {
                    if (parent.getChildCount() != 2) {
                        if (parent.getChildCount() != 3) {
                            outRect.top = space1;
                        }
                    }
                }
                break;
            case TOP:
                outRect.top = space1;
                break;
            case STAND_ITEM_DECORATION:
                outRect.bottom = space1;
                outRect.left = outRect.right = space2;
                break;

            case TOP_START_END:
                outRect.top = outRect.left = outRect.right = space1;
                break;
        }

    }

    public int dip2px(Context context, float dipValue) {
        float m = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * m + 0.5f);
    }

    public int px2dip(Context context, float pxValue) {
        float m = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / m + 0.5f);
    }
}

